// pages/xuanfeng/xuanfeng.js
Page({
  ajax(e) {
      return new Promise((resolve, reject) => {
          wx.showLoading({
              title: '请稍等...',
              mask: true
          })
          wx.request({
              url: e.url,
              timeout: e.timeout || 10000,
              complete: result => {
                  wx.hideLoading()
                  console.log(result);
                  if (result.errMsg == "request:ok" && result.statusCode == 200) {
                      resolve(result.data)
                  } else {
                      resolve(null)
                  }
              }
          })
      })
  },
  async search(e) {
      let key
      if(e) key = e.detail.value.trim()
      else key=this.data.key
      if (!key) {
          wx.showModal({
              showCancel: false,
              content: "必须输入要搜索的关键词~",
          })
          return
      }
      console.log(key)
      let url = 'https://miao101.com/search?q=' + encodeURIComponent(key)
      let html = await this.ajax({ url })
      if(html == null){
          wx.showModal({
              showCancel: false,
              content: "获取搜索列表失败，请重试~",
          })
          return
      }
      let regex = /<a href="([^"]+).+src="([^"]+)".+?alt="([^"]+)/g
      let videos = [], r,change={key}
      while (r = regex.exec(html)) {
          videos.push({
              title: r[3],
              img: r[2],
              url: r[1],
          })
      }
      console.log(videos)

      // change['menus[' + this.data.menuIndex + '].types[' + typeIndex + '].nextPage'] = 2
      change['menus[1].types[0].videos'] = videos
      this.setData(change)
  },
  play(e) {
      let index = e.currentTarget.dataset.index
      wx.navigateTo({
          url: 'player?index=' + index,
      })
  },
  async menus(e) {
      let menuIndex = e.target.dataset.index
      let oldMenuIndex =this.data.menuIndex
      if (menuIndex == 0) {
          if(oldMenuIndex==1){
             // let menu=this.data.menus[1].types[0].videos.length>0
              if(this.data.menus[1].types[0].videos.length==0){
                  this.search()
              }
              return
          }
          let menu = this.data.menus[oldMenuIndex]
          if(menu.typeIndex == null)return
          let typeIndex = menu.typeIndex
          let type = menu.types[menu.typeIndex]
          let url = 'https://miao101.com/api/load?tag=' + type.type + '&page=1'
          let html = await this.ajax({ url })
          if(html == null){
              wx.showModal({
                  showCancel: false,
                  content: "获取搜索列表失败，请重试~",
              })
              return
          }
          let regex = /<a href="([^"]+).+?"><img.+?data-src="([^"]+)".+?alt="([^"]+)/g
          let videos = [], r,change={}
          while (r = regex.exec(html)) {
              videos.push({
                  title: r[3],
                  img: r[2],
                  url: r[1],
              })
          }
          change['menus[' + oldMenuIndex + '].types[' + typeIndex + '].nextPage'] = 2
          change['menus[' + oldMenuIndex + '].types[' + typeIndex + '].videos'] = videos
          this.setData(change)
      } else {
          let change = { menuIndex }
          change['menus[' + this.data.menuIndex + '].selected'] = false
          change['menus[' + menuIndex + '].selected'] = true
          this.setData(change)
      }
  },
  async types(e) {
      let typeIndex = e.target.dataset.index
      if (typeIndex == undefined) return
      let menu = this.data.menus[this.data.menuIndex]
      let change = {}
      if (menu.typeIndex != undefined) {
          if (typeIndex == menu.typeIndex) return
          change['menus[' + this.data.menuIndex + '].types[' + menu.typeIndex + '].selected'] = false
      }
      change['menus[' + this.data.menuIndex + '].types[' + typeIndex + '].selected'] = true
      change['menus[' + this.data.menuIndex + '].typeIndex'] = typeIndex
      let type = menu.types[typeIndex]
      if (!(type.videos && type.videos.length > 0)) {
          let url = 'https://miao101.com/api/load?tag=' + type.type + '&page=1'
          let html = await this.ajax({ url })
          let regex = /<a href="([^"]+).+?"><img.+?data-src="([^"]+)".+?alt="([^"]+)/g
          let videos = [], r
          while (r = regex.exec(html)) {
              videos.push({
                  title: r[3],
                  img: r[2],
                  url: r[1],
              })
          }
          console.log("获取到视频数据")

          change['menus[' + this.data.menuIndex + '].types[' + typeIndex + '].nextPage'] = 2
          change['menus[' + this.data.menuIndex + '].types[' + typeIndex + '].videos'] = videos
      }
      this.setData(change)
  },
  async onReachBottom() {
      let menuIndex = this.data.menuIndex
      if(menuIndex == 0) return
      let menu = this.data.menus[menuIndex]
      let type = menu.types[menu.typeIndex]
      let url = 'https://miao101.com/api/load?tag=' + type.type + '&page=' + type.nextPage
      let html = await this.ajax({ url })
      let regex = /<a href="([^"]+).+?"><img.+?data-src="([^"]+)".+?alt="([^"]+)/g
      let r, change = {}, pos = type.videos.length
      while (r = regex.exec(html)) {
          change['menus[' + menuIndex + '].types[' + menu.typeIndex + '].videos[' + pos++ + ']'] = {
              title: r[3],
              img: r[2],
              url: r[1],
          }
      }
      change['menus[' + menuIndex + '].types[' + menu.typeIndex + '].nextPage'] = type.nextPage + 1
      this.setData(change)
  },
  onShow() {
      console.log('xuanfeng onShow')
  },
  onHide() {
      console.log('xuanfeng onHide')
      wx.setStorageSync('xuanfeng', this.data)
  },
  onUnload() {
      console.log('xuanfeng onUnload')
      wx.setStorageSync('xuanfeng', this.data)
  },
  wait(second) {
      return new Promise((resolve, reject) => {
          setTimeout(() => {
              reject({ success: false, arrmsg: '等待3秒钟结束~' });
          }, second * 1000);
      })
  },
  async onLoad(e) {
      // console.log('OnLoad...');
      // // setTimeout(() => {    //异步操作
      // //     console.log('等待3秒钟结束~');
      // // },3000);
      // try{
      //     let result=await this.wait(3)
      //     console.log(result)
      // }catch(e){
      //     console.log(123,e);
      // }
      // console.log('Over');

      let d = wx.getStorageSync('xuanfeng')
      if (d) {
          this.setData(d)
      }
  },
  data: {
      menuIndex: 2,
      menus: [{
          menu: '[刷新]',
      }, {
          menu: '[搜索]',
          type:[{videos:{}}],
          typeIndex:0,
      }, {
          menu: '电影',
          selected: true,
          //typeIndex:0,
          types: [
              { type: '动作片',/**selected:true, videos:[]**/ },
              { type: '喜剧片' },
              { type: '爱情片' },
              { type: '科幻片' },
              { type: '恐怖片' },
              { type: '犯罪片' },
              { type: '动漫片' },
              { type: '剧情片' },
              { type: '战争片' },
              { type: '纪录片' },
          ]
      }, {
          menu: '电视剧',
          types: [
              { type: '国产剧' },
              { type: '香港剧' },
              { type: '韩国剧' },
              { type: '欧美剧' },
              { type: '台湾剧' },
              { type: '日本剧' },
              { type: '泰国剧' },
          ]
      }, {
          menu: '综艺',
          types: [
              { type: '大陆综艺' },
              { type: '日韩综艺' },
              { type: '港台综艺' },
              { type: '欧美综艺' },
          ]
      }, {
          menu: '动漫',
          types: [
              { type: '国产动漫' },
              { type: '港台动漫' },
              { type: '日韩动漫' },
              { type: '欧美动漫' },
              { type: '海外动漫' },
          ]
      }, {
          menu: '体育',
          types: [
              { type: '足球' },
              { type: '篮球' },
              { type: '网球' },
              { type: '斯诺克' },
          ]
      }]
  },
})